import { useModel } from '@umijs/max';
import { useEffect, useState } from 'react';
import { Socket, io } from 'socket.io-client';
import { history } from 'umi';
import { isNotBlank } from 'web-plugin-utils';

export default () => {
  const [peer, setPeer] = useState<Socket>();
  const { initialState } = useModel('@@initialState');

  useEffect(() => {
    if (
      history.location.pathname === '/meet' ||
      history.location.pathname === '/login'
    ) {
      return;
    }
    // eslint-disable-next-line eqeqeq
    if (initialState == undefined) {
      return;
    }

    let _peer: Socket;
    if (isNotBlank(initialState.nickname)) {
      const socket = io(`http://${initialState.serverIp}:9999`, {
        reconnectionDelayMax: 10000,
        transports: ['websocket'],
        auth: {
          config: initialState,
        },
      });

      socket.on('connect', () => {
        console.log('连接SocketId: ' + socket.id);
      });

      socket.on('disconnect', (reason) => {
        if (reason === 'io server disconnect') {
          // the disconnection was initiated by the server, you need to reconnect manually
          socket.connect();
        }
        // else the socket will automatically try to reconnect
      });
      socket.on('error', (error) => {
        console.log(error);
      });

      setPeer(socket);
    }

    return () => {
      _peer?.disconnect();
    };
  }, [initialState]);
  return {
    peer,
  };
};
